package PriorityQueue;

public class OrderedPriorityQueue<E extends Priority> implements Queue<E>{

    private Priority[] arr;
    private int size;

    public OrderedPriorityQueue(int capacity) {
        arr = new Priority[capacity];
    }

    @Override
    public boolean offer(E value) {
        if (isFull()) {
            return false;
        }
        //先找到优先级比value的优先级大的索引
        int i = size - 1;
        while (i >= 0 && arr[i].priority() > value.priority()) {
            arr[i+1] = arr[i];
            i--;
        }
        arr[i+1] = value;
        size++;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        E str = (E)arr[size - 1];
        size--;
        arr[size] = null;
        return str;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        E str = (E)arr[size - 1];
        return str;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == arr.length;
    }
}
